import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

import home from '../pages/home.vue'
import follow from '../pages/follow.vue'
import column from '../pages/column.vue'
import user from '../pages/user.vue'
import reg from '../pages/reg.vue'
import login from '../pages/login.vue'
import NoPage from '../pages/no-page.vue'
import detail from '../pages/detail.vue'

import axios from './axios.js'

let routes = [
  {path:'/home', component:home},
  {path:'/home/:_id', component:detail,name:'home-detail',meta:{path:'detail'}},
  {path:'/follow', component:follow},
  {path:'/follow/:_id', component:detail,meta:{path:'detail'}},
  {path:'/column', component:column},
  {path:'/column/:_id', component:detail,meta:{path:'detail'}},
  {path:'/user', component:user},
  {path:'/login', component:login},
  {path:'/reg', component:reg},
  {path:'/',redirect:'/home'},
  {path:'*', component:NoPage},
];

let router = new VueRouter({
  routes,
  mode:'history'
})

router.beforeEach((to,from,next)=>{
	//校验token ===>  组件还需读自身数据
	let path = to.path;
	if(path.includes('/login') || path.includes('/reg')){
		next()
	}else{
		axios({
			url:'/is-token',
		}).then(
			res=>{
				if(res.err===2){
					console.log('守卫',res)
					next('/login?path=${to.fullpath}')
				}else{
					next()
				}
			}
		)
	}
	//校验+数据预载  ===> 组件直接渲染
	/* console.log('beforeEach', to.path, to.params, to.query)
	
	let path = to.path;
	
	if(path.includes('/login') || path.includes('/reg')){
	  next()
	}else{
	  
	  //准备集合
	  let collectionName = '';
	  
	  if(/home/.test(path)) collectionName = 'home';
	  if(/follow/.test(path)) collectionName = 'follow';
	  if(/column/.test(path)) collectionName = 'column';
	  if(/user/.test(path)) collectionName = 'user';
	  if(/detail/.test(path))  collectionName = to.query.collectionName;
	  let url = to.params._id ? 
	    `/news/${collectionName}/${to.params._id}` :
	    `/news/${collectionName}`
	  url = collectionName == 'user' ? `/${collectionName}` : url;
	  axios({
	    url,
	    // params:to.query,
	  }).then(
	    res=>{
	      if(res.err===2 && !to.path.includes('/login')){
	        console.log('守卫',res)
	        next(`/login?p=${to.fullPath}`)
	      }else if(res.err===1){
	        next();//不存在接口
	      }else{
	        to.query.data = res.data;
	        next()
	      }
	    }
	  )
	  
	} */
})
export default router;